// Copyright (C), 2012-2018, Sichuan Xiaoka Technology Co., Ltd.
package utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * jwt工具类
 * @author  张鹏
 */
@Slf4j
public class JwtUtils {


    /**
     * 由字符串生成加密key.
     *
     * @return.
     */
    public static SecretKey generalKey(String stringKey) {
        byte[] encodedKey = stringKey.getBytes();
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 构建jwt
     *
     * @param object 存放的信息
     * @param expTime 过期时间，以分钟为单位
     * @return token
     */
    public static String createJwt(Object object, int expTime) {

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String subject = objectMapper.writeValueAsString(object);
            //aes加密
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
            //签发时间 过期时间
            Calendar calendar = Calendar.getInstance();
            Calendar expCalendar = Calendar.getInstance();
            expCalendar.add(Calendar.MINUTE, expTime);
            SimpleDateFormat sdf3=new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");
            log.info(sdf3.format(expCalendar.getTime()));

            SecretKey key = generalKey("");
            JwtBuilder builder = Jwts.builder()
                    .setIssuedAt(calendar.getTime())
                    .setSubject(new String(subject))
                    .signWith(signatureAlgorithm, key)
                    .setExpiration(expCalendar.getTime());
            return builder.compact();
        }catch (JsonProcessingException e){
            log.info("JWT failed to issue",e);
        }
        return null;
    }


    /**
     * 解密jwr
     *
     * @param jwt
     * @return
     */
    public static String parseJwt(String jwt) {
        try {
            SecretKey key = generalKey("");
            Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
            String subject = claims.getSubject();
//            //aes解密
            return subject;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
